package cc.laop.support.filter;

import cc.laop.business.system.ResourceBusiness;
import cc.laop.entity.system.Resource;
import cc.laop.utils.ApplicationUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.List;

public class CustomUrlPermissionFilter extends AuthorizationFilter {

    private ResourceBusiness resourceBusiness;

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        String requestUrl = WebUtils
                .getPathWithinApplication(WebUtils.toHttp(request));
        if (resourceBusiness == null) {
            resourceBusiness = (ResourceBusiness) ApplicationUtil
                    .getBean(ResourceBusiness.class);
        }
        Resource resource = new Resource();
        resource.setUrl(requestUrl.substring(1));
        List<Resource> resList = resourceBusiness.select(resource);
        boolean ispermitted = false;
        if (CollectionUtils.isNotEmpty(resList)) {
            for (Resource res : resList) {
                ispermitted = subject.isPermitted(res.getPermission());
                if (ispermitted) {
                    break;
                }
            }
        } else {
            ispermitted = true;
        }
        return ispermitted;
    }

}
